import $ from 'jquery';
import {toast} from './tools'
import auth from './auth';

function ajax(type, url, data, contentType = 'application/json'){
  let token = auth.getToken();
  let headers = undefined;
  if(token){
    headers = {
      Authorization: 'Bearer '+token,
    }
  }
  return new Promise((resolve, reject)=>{
    $.ajax({
      type: type,
      url: url,
      data: (type==='POST' && contentType==='application/json') ? JSON.stringify(data):data,
      processData: contentType === false?false: true,
      contentType: contentType,
      headers: headers,
      success:function(data){
        if(data && data.code === 2000){
          resolve(data.data);
          return;
        }

        toast(`${data.msg}`, "error")
        // 非法token或者token过期，跳转到登陆页
        if(data.code === 4000 || data.code ===4001){
          auth.clearToken();
          location.href = '/#/login';
        }
        reject(data)
      },
      error:function(xhr, textStatus, errorThrown){
        toast(`系统开小差了，请稍后再试吧！(${textStatus})`, "error")
        // eslint-disable-next-line
        console.log(`status: ${textStatus}\n ${xhr.responseText}`);
        reject(xhr, textStatus, errorThrown);
      },
    })
  })
}

export const get = (url, data, contentType) => {
  return ajax("GET", url, data, contentType)
};

export const post = (url, data, contentType) => {
  return ajax("POST", url, data, contentType)
};
